<?php
//decode by http://奥森世纪/
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/1/19
 * Time: 19:34
 */

namespace app\home\controller;

use app\admin\model\Config;
use app\admin\model\TaskCategory;
use app\admin\model\Uploads;
use app\home\model\Area;
use app\home\model\CreditRecord;
use app\home\model\Member;
use think\Db;
use think\Log;
use think\Cache;

class Mytask extends Base {

    public function index(){
        $member = $this->checkLogin();

        $params = array();
        $params['uid'] = $member['uid'];
        $params['category_type'] = "all";
        $data = $this->_get_data($params);
		
        $data['category_type'] = "all";
        return $this->fetch('index', $data);
    }

    public function category() {
        $member = $this->checkLogin();

        $params = array();
        $params['uid'] = $member['uid'];
        $params['category_type'] = trim(params('t'));
        $data = $this->_get_data($params);

        $data['category_type'] = $params['category_type'];

        return $this->fetch('index', $data);
    }

    private function _get_data($params = array()) {
        $pszie = 15;
        $tasks = \app\home\model\MyTask::getListByParams($params, $pszie);
        $model=db('redpackage');
	$see_model=db('seepackage');
	$member=$this->member;
	foreach($tasks as &$v){
	
		$v['is_send_redpackage']=$model->where(['uid'=>$member['uid'],'task_id'=>$v['id']])->find()?1:0;
		
		$seepackage=$see_model->where(['uid'=>$member['uid'],'task_id'=>$v['id']])->find();
		//增加发布任务用户图像
		$userInfo=$member->getUserInfoById($member['uid']);
		$avatar=$userInfo['avatar'];
		$v['is_send_seepackage']=$seepackage?1:0;
		$v['seepackage_price']=$seepackage?$seepackage['money']:0;
		$v['avatar']=$avatar?$avatar:0;

	}
        if(request()->isAjax()){
            if(empty($tasks)){
                message('没有更多信息','','error');
            }
            $view = $params['category_type'] == "audit" ? '_audit_list' : '_list';
            $html = $this->fetch($view, [
                'tasks' => $tasks
            ]);
            message($html,'','success');
        }
        $count = \app\home\model\MyTask::getCountByParams($params);
        $pageCount = ceil($count/$pszie);

        $setting = [];
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['top_fee'])){
                $setting['top_fee'] = intval($setting['top_fee']);
            }
        }
	

        return [
            'tasks' => $tasks,
            'setting' => $setting,
            'pageCount' => $pageCount
        ];
    }

    public function del() {
        $member = $this->checkLogin();

        $id = intval(params('id'));
        $tasks = \app\home\model\MyTask::getInfoById($id);
        if (is_null($tasks)) {
            message('删除失败:-1','','error');    
        }
        if ($tasks['uid'] != $member['uid']) {
            message('删除失败:-2','','error');       
        }
        /*if($tasks['join_num'] > 0){
            message('删除失败:-3','','error');
        }*/
        $taskjoin = \db('task_join')->where(['task_id'=>$tasks['id']])->select();
      	foreach($taskjoin as $value){
         	if($value['status']==2 && $value['delflag'] == 1){
              message('还有任务未审核,无法删除','','error');
            }
          if($value['status']==1 && $value['delflag'] == 1){
              message('还有用户正在接单,无法删除','','error');
            }
          if($value['status']==4 && $value['delflag'] == 1){
              message('锁定名额中,需等24小时才可删除','','error');
            }
            if($value['is_shensu']==1){
              message('有用户发起申诉，结束后方可删除','','error');
            }
        }

        Db::startTrans();

        $result = \app\home\model\MyTask::delById($id);
        if (!$result) {
            message('删除失败:-3','','error');
        }

        $insert_task_id = $tasks['id'];

        //删除任务时需要退还金额
        if($tasks['amount']>0){
            $status1 = Member::updateCreditById($tasks['uid'], 0, $tasks['amount']);
            if(!$status1){
                Db::rollback();
                message('删除失败:-4','','error');
            }
            //分别记录积分和余额记录
            
            if($tasks['amount']>0){
                $status3 = CreditRecord::addInfo([
                    'uid' => $tasks['uid'],
                    'type' => 'credit2',
                    'num' => $tasks['amount'],
                    'title' => '删除任务',
                    'remark' => "任务[$insert_task_id]-" . $tasks['title'] . "删除成功，退还{$tasks['amount']}余额。",
                    'create_time' => TIMESTAMP
                ]);
                if(!$status3){
                    Db::rollback();
                    message('删除失败:-6','','error');
                }
            }
        }

        Db::commit();

        message('删除成功','reload','success');
    }
    //2019-05-29新添加模块
    public function serav(){
        $member = $this->checkLogin();
      	
      
     /* $daishangxian = \app\home\model\MyTask::getCountByParams(['uid'=>$member['uid'],'category_type'=>'wait']);
        $zhanshizhong = \app\home\model\MyTask::getCountByParams(['uid'=>$member['uid'],'category_type'=>'ing']);
      	$yizanting =  \db('task')->where(['uid'=>$member['uid'],'is_stop'=>1,'out_stock_flag'=>0,'is_complete'=>0])->count();
      
      */
      	$daishangxian = \db('task')->where(['uid'=>$member['uid'],'is_display'=>0])->count();
        $zhanshizhong = \db('task')->where(['uid'=>$member['uid'],'is_stop'=>0,'start_time'=>['lt',time()],'end_time'=>['gt',time()],'is_display'=>1,'out_stock_flag'=>0])->count();
      	$yizanting =  \db('task')->where(['uid'=>$member['uid'],'is_stop'=>1,'out_stock_flag'=>0,'is_complete'=>0,'is_display'=>1])->count();
     	 $shibai = \db('task')->where(['uid'=>$member['uid'],'is_display'=>'-1'])->count();
      $yixiajia = \db('task')->where(['uid'=>$member['uid'],'out_stock_flag'=>1,'is_complete'=>1])->count();
      $weishenhe = \db('task_join')->alias('n')->join("tb_task m","m.id=n.task_id")->where(['m.uid'=>$member['uid'],'m.out_stock_flag'=>0,'m.is_complete'=>0,'n.status'=>2])->count();
      $list=[
      	'daishangxian'=>$daishangxian,
        'zhanshizhong'=>$zhanshizhong,
        'yizanting'=>$yizanting,
        'shibai'=>$shibai,
        'yixiajia'=>$yixiajia,
        "weishenhe"=>$weishenhe
      ];
      //2019-08-05 修改
        $levels = Db::name("member")->where("uid = {$member['uid']}")->find();
        $msg_level = Db::name("member_level")->where("level = {$levels['level']}")->find();
        return $this->fetch(__FUNCTION__,[
            'uid'=>$member['uid'],
            'num'=>$member['credit2'],
            'img'=>$member['avatar'],
            'nickname'=>$member['nickname'],
            'msg_levels'=>$msg_level['title'],
          	'list'=>$list,
          	'is_vip'=>$member['level_time']>time()?1:0,
        ]);
    }

    public function check() {
        to_json(0, '');
    }

    public function audit2() {
        $member = $this->checkLogin();

        $params = array();
        $params['uid'] = $member['uid'];
        $params['category_type'] = "audit";
        $data = $this->_get_data($params);


        $data['category_type'] = $params['category_type'];

        return $this->fetch(__FUNCTION__, $data);
    }
    
    public function audit() {
        $member = $this->checkLogin();

        $params = array();
        $params['uid'] = $member['uid'];
        $params['category_type'] = "audit";
      

        
		$task_ids = \db('task_join')->alias('n')->join("tb_task m","m.id=n.task_id")->where(['m.uid'=>$member['uid'],'m.out_stock_flag'=>0,'m.is_complete'=>0,'n.status'=>2])->column('task_id');
	
	//	$data=db('task')->where(['id'=>['in',$task_ids]])->select();

		    
		$params['task_ids']=implode(',',$task_ids);
    
        $data = $this->_get_data($params);

        $data['category_type'] = $params['category_type'];

        return $this->fetch(__FUNCTION__,$data);
    }
    


    public function audit3() {
        $member = $this->checkLogin();

        $params = array();
        $params['uid'] = $member['uid'];
        $params['category_type'] = "audit";
      
		$task_ids = \db('task_join')->alias('n')->join("tb_task m","m.id=n.task_id")->where(['m.uid'=>$member['uid'],'m.out_stock_flag'=>0,'m.is_complete'=>0,'n.status'=>2])->select();
	
	//	$data=db('task')->where(['id'=>['in',$task_ids]])->select();

		    
		$params['task_ids']=implode(',',$task_ids);
    
        $data = $this->_get_data($params);

        $data['category_type'] = $params['category_type'];

        return $this->fetch(__FUNCTION__,$data);
    }

    

    public function setTop() {
        $member = $this->checkLogin();   
        $id = intval(params('id'));
        $tasks = \app\home\model\MyTask::getInfoById($id);
      
        if (is_null($tasks)) {
            message('置顶失败:-1','','error');    
        }
        if ($tasks['uid'] != $member['uid']) {
            message('置顶失败:-2','','error');       
        }

        $setting = [];
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['top_fee'])){
                $setting['top_fee'] = intval($setting['top_fee']);
            }
        }

        if(!isset($setting['top_fee'])){
            $setting['top_fee'] = 0;
        }
       if(!isset($setting['vipzhiding'])){
            $setting['vipzhiding'] = 0;
        }

        if(!isset($setting['top_max_hour'])){
            $setting['top_max_hour'] = 1;
        }
        $params = array_trim(request()->post());
        $params['hour'] = intval($params['hour']);
      	
      //修改VIP赠送置顶时间不收费
      	$membertoptime = $member['toptime'] - $params['hour'];
      	if($membertoptime >= 0){
          $paramshour = 0;
        }else{
          $paramshour = (-$membertoptime);
          $membertoptime = 0;
        }
      if($member['level'] != 1){
      	$settingtopfee = $setting['vipzhiding'];
      }else{
        $settingtopfee = $setting['top_fee'];
      }
      
        $top_fee = $paramshour *$settingtopfee ;
		
     	//message('置顶时间最多' . $params['hour'] . '小时','','error');
        if ($params['hour'] > $setting['top_max_hour']) {
            message('置顶时间最多' . $setting['top_max_hour'] . '小时','','error');
        }

        //判断余额或者积分是足够
        if($top_fee > $member['credit2']){
            message('账户余额不足','','error');
        }
        Db::startTrans();
      if($member['toptime'] != 0){
      	$memberres = \db('member')->where(['uid'=>$member['uid']])->data(['toptime'=>$membertoptime])->update();
      if(!$memberres){
        Db::rollback();
            message('置顶失败:-6','','error');
      }
      }
      	
      
      if($tasks['top_end_time'] >= time()){
          $update = [
            'top_hour' => $params['hour']+$tasks['top_hour'],
            'top_fee' => $top_fee+$tasks['top_fee'],
            'top_end_time' => $tasks['top_end_time'] + ($params['hour'] * 60 * 60)
        ];
        }
        else{
          $update = [
            'top_time' => TIMESTAMP,
            'top_hour' => $params['hour'],
            'top_fee' => $top_fee,
            'top_end_time' => TIMESTAMP + ($params['hour'] * 60 * 60)
        ];
        }
        
        $status0 = \app\home\model\Task::updateInfoById($id, $update);
        if(!$status0){
            Db::rollback();
            message('置顶失败:-3','','error');
        }

        if($top_fee>0){
            $status1 = Member::updateCreditById($member['uid'], 0, -$top_fee);
            if(!$status1){
                Db::rollback();
                message('置顶失败:-4','','error');
            }
            $status3 = CreditRecord::addInfo([
                'uid' => $member['uid'],
                'type' => 'credit2',
                'num' => -$top_fee,
                'title' => '置顶任务',
                'remark' => "任务[" . $tasks['id'] . "]-" . $tasks['title'] . "置顶成功".$params['hour']."小时，扣除{$top_fee}余额。",
                'create_time' => TIMESTAMP
            ]);
            if(!$status3){
                Db::rollback();
                message('置顶失败:-5','','error');
            }
        }

        Db::commit();
	
		Cache::set('is_top',1);

        message('置顶成功','reload','success');
    }






    
    //下架
    public function outstock(){
        $tasks = db('task')->where('id',input('id'))->find();
      	$taskjoin = db('task_join')->where(['task_id'=>$tasks['id']])->select();
      	foreach($taskjoin as $value){
         	if($value['status']==2 && $value['delflag'] == 1){
              message('还有任务未审核,无法下架','','error');
            }
          if($value['status']==1 && $value['delflag'] == 1){
              message('还有用户正在接单,无法下架','','error');
            }
          if($value['status']==4 && $value['delflag'] == 1){
              message('锁定名额中,需等24小时才可下架','','error');
            }
            if($value['is_shensu']==1){
              message('有用户发起申诉，结束后方可下架','','error');
            }
        }
        
        
        $taskService = \think\Loader::model("Task", 'service');
        $taskService->outStockTask($tasks);
        
       
        Db::startTrans();
		//退还红包金额
		$task_id=input('id');
		$uid=$tasks['uid'];
	
		$redpackage=\db('redpackage')->where(['task_id'=>$task_id,'is_over'=>0])->find();
		if($redpackage){
			$has_send_money=\db('redpackage_record')->where(['task_id'=>$task_id,'uid'=>['neq',0]])->sum('money');
			$has_send_number=\db('redpackage_record')->where(['task_id'=>$task_id,'uid'=>['neq',0]])->count();

			if($has_send_money <$redpackage['money']){
				//剩余金额
				$left_money=$redpackage['money']-$has_send_money;
		
				$member=db('member')->where('uid',$uid)->find();
				$credit2 = $member['credit2']+$left_money;
					    
					       // $res1 = \db('member')->where(['uid'=>$uid])->data(['credit2'=>$credit2])->update();
					          $res1 = Member::updateCreditById($uid, 0, $left_money);
					            if(!$res1){
						            Db::rollback();
						            message('操作失败:-3','','error');
						        }
		
					        $creditdata = array(
					            'uid'=>$uid,
					            'type'=>'credit2',
					            'num'=>'+'.$left_money,
					            'title'=>'下架任务返还红包余额',
					            'remark'=>'下架任务'.$task_id.'返还红包余额'.$left_money,
					            'create_time'=>time(),
					            'balance'=>$credit2,    //追加后的余额
					        );
					        $res3 = \db('credit_record')->data($creditdata)->insert();
					        if(!$res3){
					            Db::rollback();
					            message('下架失败:-5','','error');
					        }
					        
					        //标记
							\db('redpackage')->where(['task_id'=>$task_id])->setField('is_over',1);
							
							\db('redpackage_record')->where(['task_id'=>$task_id,'uid'=>0])->setField('is_back',1);
					

			}
			
		}
        
          Db::commit();
        back_seepackage($task_id,$uid);
        
        message('下架成功','','success');
    }

















    public function outstock2() {
    	
    	
    	
        $member = $this->checkLogin();

        $id = intval(params('id'));
        $tasks = \app\home\model\MyTask::getInfoById($id);
        if (is_null($tasks)) {
            message('下架失败:-1','','error');
        }
        if ($tasks['uid'] != $member['uid']) {
            message('下架失败:-2','','error');
        }
      	$taskjoin = \db('task_join')->where(['task_id'=>$tasks['id']])->select();
      	foreach($taskjoin as $value){
         	if($value['status']==2 && $value['delflag'] == 1){
              message('还有任务未审核,无法下架','','error');
            }
          if($value['status']==1 && $value['delflag'] == 1){
              message('还有用户正在接单,无法下架','','error');
            }
            if($value['is_shensu']==1){
              message('有用户发起申诉，结束后方可删除','','error');
            }
          if($value['status']==4 && $value['delflag'] == 1){
              message('锁定名额中,需等24小时才可下架','','error');
            }
            
        }
        

        $taskService = \think\Loader::model("Task", 'service');
        $taskService->outStockTask($tasks);

Db::startTrans();
		//退还红包金额
		$task_id=$tasks['id'];
		$redpackage=\db('redpackage')->where(['task_id'=>$task_id,'is_over'=>0])->find();
		if($redpackage){
			$has_send_money=\db('redpackage_record')->where(['task_id'=>$task_id,'uid'=>['neq',0]])->sum('money');
			$has_send_number=\db('redpackage_record')->where(['task_id'=>$task_id,'uid'=>['neq',0]])->count();
			
			if($has_send_money <$redpackage['money']){
				//剩余金额
				$left_money=$redpackage['money']-$has_send_money;
				
				$credit2 = $member['credit2']+$left_money;
					    
					        $res1 = \db('member')->where(['uid'=>$member['uid']])->data(['credit2'=>$credit2])->update();
					            if(!$res1){
						            Db::rollback();
						            message('操作失败:-3','','error');
						        }
		
					        $creditdata = array(
					            'uid'=>$member['uid'],
					            'type'=>'credit2',
					            'num'=>'+'.$left_money,
					            'title'=>'下架任务返还红包余额',
					            'remark'=>'下架任务'.$task_id.'返还红包余额'.$left_money,
					            'create_time'=>time(),
					            'balance'=>$credit2,    //追加后的余额
					        );
					        $res3 = \db('credit_record')->data($creditdata)->insert();
					        if(!$res3){
					            Db::rollback();
					            message('下架失败:-5','','error');
					        }
					        
					        //标记
							\db('redpackage')->where(['task_id'=>$task_id])->setField('is_over',1);
							
							\db('redpackage_record')->where(['task_id'=>$task_id,'uid'=>0])->setField('is_back',1);
					
			}
			
		}
	
Db::commit();
        message('下架成功','reload','success');
    }
    
    
    
    public function stopstock() {
        $member = $this->checkLogin();

        $id = intval(params('id'));
        $status = @intval(params('status'));
        $tasks = \app\home\model\MyTask::getInfoById($id);
        if (is_null($tasks)) {
            message('暂停失败:-1','','error');
        }
        if ($tasks['uid'] != $member['uid']) {
            message('暂停失败:-2','','error');
        }
        if($status == 1){
        	if($tasks['is_dj'] ==0){
            	message('违规已被冻结不可开启','','error');
        	}
        	if($tasks['out_stock_flag'] ==1){
            	message('已下架不可开启','','error');
        	}
            Db::name("task")->where(['id'=>$id])->update(['is_stop'=>0]);
            message('开启任务成功','reload','success');
        }else{
            Db::name("task")->where(['id'=>$id])->update(['is_stop'=>1]);
            message('暂停任务成功','reload','success');
        }
    }

    public function iszhuijia()
    {
        $member = $this->checkLogin();
        $taskid = intval(params('taskid'));
        $piaoshu = intval(params('piaoshu'));
        if($piaoshu<1){
        	message('非法','','error');
        }
        $tasks = \app\home\model\MyTask::getInfoById($taskid);
        if(empty($taskid) || empty($piaoshu)){
            message('追加票数失败:-1','','error');
        }
        if($tasks['uid'] != $member['uid']){
            message('追加票数失败:-2','','error');
        }
        if($tasks['out_stock_flag'] ==1){
            message('已下架不可追票','','error');
        }
        $setting =[];
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            
        }
        //手续费按是否会员不同
        if($member['level']>1){
        	$setfree = $setting['fee_member']/100;
        }else{
        	$setfree = $setting['fee']/100;
        }
        $fee = $tasks['unit_price']*(1+$setfree)*$piaoshu;
        if($member['credit2'] < $fee){
            message('账户余额不足','','error');
        }
        $credit2 = $member['credit2']-$fee;
        Db::startTrans();
        $res1 = \db('member')->where(['uid'=>$member['uid']])->data(['credit2'=>$credit2])->update();
        if(!$res1){
            Db::rollback();
            message('追加票数失败:-3','','error');
        }

        $amount = $tasks['unit_price']*(1+$tasks['fee'])*$piaoshu+$tasks['amount'];
        $give_credit2 = $tasks['unit_price']*$piaoshu+$tasks['give_credit2'];
        $ticket = $piaoshu+$tasks['ticket_num'];

        $creditdata = array(
            'uid'=>$member['uid'],
            'type'=>'credit2',
            'num'=>'-'.$tasks['unit_price']*(1+$tasks['fee'])*$piaoshu,
            'title'=>'任务票数追加',
            'remark'=>$tasks['id'].'追加票数'.$piaoshu,
            'create_time'=>time(),
            'balance'=>$credit2,    //追加后的余额
        );
        $res3 = \db('credit_record')->data($creditdata)->insert();
        if(!$res3){
            Db::rollback();
            message('追加票数失败:-5','','error');
        }

        $data = array(
          'ticket_num'=>$ticket,
          'give_credit2'=>$give_credit2,
          'amount'=>$amount
        );
        $res2 = \db('task')->where(['id'=>$tasks['id']])->data($data)->update();
        if(!$res2){
            Db::rollback();
            message('追加票数失败:-4','','error');
        }
        Db::commit();
        message('追加票数成功','reload','success');
    }
  public function jiashi(){
     $member = $this->checkLogin();
        $taskid = intval(params('taskid'));
        $tianshu = intval(params('tianshu'));
        $tasks = \app\home\model\MyTask::getInfoById($taskid);
        if(empty($taskid) || empty($tianshu)){
            message('追加天数失败:-1','','error');
        }
        if($tasks['uid'] != $member['uid']){
            message('追加天数失败:-2','','error');
        }
        if($tasks['out_stock_flag'] ==1){
            message('已下架不可追时','','error');
        }
    $endtime =strtotime($tasks['end_time'])+$tianshu*24*60*60;
            //dump($tasks['end_time']);exit;
       $res2=\db('task')->where(['id'=>$tasks['id']])->data(['end_time'=>$endtime])->update();
      if(!$res2){
          Db::rollback();
          message('追加天数失败:-3','','error');
      }
      Db::commit();
      message('追加天数成功','reload','success');
  }
  public function jiajia(){
     $member = $this->checkLogin();
     $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            
          if($member['level']==1){
            if(!empty($setting['fee'])){
                $setting['fee'] = round(floatval($setting['fee']*0.01),2);
            }
          }else{
            if(!empty($setting['fee_member'])){
                $setting['fee'] = round(floatval($setting['fee_member']*0.01),2);
            }
          }
            
        } 
        $taskid = intval(params('taskid'));
        $credit2 = round(params('jiajia'),1);
        if($credit2 <=0){
        	message('非法','','error');
        }
        $tasks = \app\home\model\MyTask::getInfoById($taskid);
        if(empty($taskid) || empty($credit2)){
            message('追加单价失败:-1','','error');
        }
        if($tasks['uid'] != $member['uid']){
            message('追加单价失败:-2','','error');
        }
        if($tasks['out_stock_flag'] ==1){
            message('已下架不可追加','','error');
        }
        $task_join = db('task_join')->where('task_id',$taskid)->where('status','<',3)->where('delflag',1)->select();
        if(count($task_join) > 0){
        	message('有任务正在进行中不可加价','','error');
        }
        $num = $tasks['ticket_num']-$tasks['join_num'];
        if($num<1){
        	message('任务不足','','error');
        }
        $money = round(($credit2+$credit2*$setting['fee'])*$num,2);
    	$give_credit2 =$tasks['unit_price']+$credit2;
    	if($member['credit2']<$money){
    		message('余额不足','','error');
    	}
    	db('member')->where('uid',$member['uid'])->setDec('credit2',$money);
       $res2=\db('task')->where(['id'=>$tasks['id']])->data(['unit_price'=>$give_credit2])->update();
       CreditRecord::addInfo([
                'uid' => $member['uid'],
                'type' => 'credit2',
                'num' => -$money,
                'title' => '任务加价',
                'remark' => "任务[" . $taskid . "]-" . $tasks['title'] . "加价成功".$credit2."元，扣除{$money}余额。",
                'create_time' => TIMESTAMP
            ]);
      if(!$res2){
          Db::rollback();
          message('追加单价失败:-3','','error');
      }
      Db::commit();
      message('追加单价成功','reload','success');
  }
  
      public function share() {
        $member = $this->checkLogin();
    
        $task_id=request()->param('task_id');
        if($task_id){

            $task_info=db('task')->where('id',$task_id)->find();
            $today=date('Ymd');
            $share_time=date('Ymd',$task_info['share_time']);
            if($member['uid'] == $task_info['uid'] && $share_time !=$today){
                $rst=db('task')->where('id',$task_info['id'])->setField('share_time',time());
                if($rst){
                    echo 1;
                   // message('更新成功','','success');
                }else{
                    echo 0;
                    message('更新失败','','error');

                }
            }
        }
    }
  

//发红包

    public function send_redpackage()
    {
        $member = $this->checkLogin();
        $task_id = intval(params('task_id'));
         $money = intval(params('money'));
        $number = intval(params('number'));
 
        if($money<1){
        	message('金额不能小于1','','error');
        }
        if($number<10){
        	message('红包个数不能小于10','','error');
        }
        
        if($money/$number<0.1){
        		message('红包平均金额最低不能小于0.1','','error');
        }
        if(!$task_id){
        	message('参数错误','','error');
        }
        
        
        
        $is_send=\db('redpackage')->where(['uid'=>$member['uid'],'task_id'=>$task_id])->find();
        if($is_send){
        	 message('已发送红包，不能重复发送','','error');
        }
        $tasks = \app\home\model\MyTask::getInfoById($task_id);
     
        if(empty($tasks)){
            message('发红包失败:-1','','error');
        }
        if($tasks['uid'] != $member['uid']){
            message('发红包失败:-2','','error');
        }
        if($tasks['out_stock_flag'] ==1){
            message('任务已下架，不能发红包','','error');
        }
        $setting =[];
        $config = Config::getInfo();
     
        if($member['credit2'] < $money){
            message('账户余额不足','','error');
        }
        $credit2 = $member['credit2']-$money;
        Db::startTrans();
        $res1 = \db('member')->where(['uid'=>$member['uid']])->data(['credit2'=>$credit2])->update();
        if(!$res1){
            Db::rollback();
            message('发红包失败:-3','','error');
        }



        $creditdata = array(
            'uid'=>$member['uid'],
            'type'=>'credit2',
            'num'=>'-'.$money,
            'title'=>'发红包',
            'remark'=>'任务'.$tasks['id'].'发红包扣除'.$money,
            'create_time'=>time(),
            'balance'=>$credit2,    //追加后的余额
        );
        $res3 = \db('credit_record')->data($creditdata)->insert();
        if(!$res3){
            Db::rollback();
            message('发红包失败:-5','','error');
        }
	
		//添加数据
        $data = array(
          'number'=>$number,
          'money'=>$money,
          'task_id'=>$task_id,
          'uid'=>$member['uid'],
          'add_time'=>time(),
          'is_over'=>0,
          
        );
        $res2 = \db('redpackage')->insert($data);
        if(!$res2){
            Db::rollback();
            message('发红包失败:-4','','error');
        }
        
        
	    $redpackage_list=random_red($money, $number, round($money*0.15,2), 0.1);

	    if($redpackage_list){
	    	shuffle($redpackage_list);
			//插入数据库
				$redpackage_record_model=db('redpackage_record');
	        	foreach($redpackage_list as $v){
	        		$d=[
	        			'task_id'=>$task_id,
	        			'money'=>$v
	        			];
	        		$res3=	$redpackage_record_model->insert($d);
	        	}
		    if(!$res3){
	            Db::rollback();
	            message('发红包失败:-5','','error');
	        }
	        	
	    }else{
	    	Db::rollback();
	        message('发红包失败:-6','','error');
	    }
        	
        
        Db::commit();
        message('发红包成功','reload','success');
    }




//发浏览红包

    public function send_see()
    {
        $member = $this->checkLogin();
        $task_id = intval(params('task_id'));
         $money = params('money');
        $number = intval(params('number'));

        if($money<0.02){
        	message('单个红包金额不能小于0.02','','error');
        }
        if($number<500){
        	message('红包个数不能小于500','','error');
        }
        
        if(!$task_id){
        	message('参数错误','','error');
        }
        
        
        $tasks = \app\home\model\MyTask::getInfoById($task_id);
     
        if(empty($tasks)){
            message('发红包失败:-1','','error');
        }
        if($tasks['uid'] != $member['uid']){
            message('发红包失败:-2','','error');
        }
        if($tasks['out_stock_flag'] ==1){
            message('任务已下架，不能发红包','','error');
        }
     
        //是否已发送浏览红包
        
        $is_where=[
        	'task_id'=>$task_id,
        	'uid'=>$member['uid'],
        	];
		$send_info= \db('seepackage')->where($is_where)->find();
		if($send_info){
			
			$money=$send_info['money'];

		}
		
    	$total_money=$money*$number;
     
        if($member['credit2'] < $total_money){
            message('账户余额不足','','error');
        }
        
        
        
        $credit2 = $member['credit2']-$total_money;
        Db::startTrans();
        $res1 = \db('member')->where(['uid'=>$member['uid']])->data(['credit2'=>$credit2])->update();
        if(!$res1){
            Db::rollback();
            message('发红包失败:-3','','error');
        }


        $creditdata = array(
            'uid'=>$member['uid'],
            'type'=>'credit2',
            'num'=>'-'.$total_money,
            'title'=>'发红包',
            'remark'=>'任务'.$tasks['id'].'发红包扣除'.$total_money,
            'create_time'=>time(),
            'balance'=>$credit2,    //追加后的余额
        );
        $res3 = \db('credit_record')->data($creditdata)->insert();
        if(!$res3){
            Db::rollback();
            message('发红包失败:-5','','error');
        }
	if($send_info){
		//添加数据
        $data = array(
          'number'=>$number+$send_info['number'],
          'money'=>$money,
          'total_money'=>$total_money+$send_info['total_money'],
          'task_id'=>$task_id,
          'uid'=>$member['uid'],
          'is_over'=>0,
          'is_back'=>0,
          
        );
        $res2 = \db('seepackage')->where('seepackage_id',$send_info['seepackage_id'])->update($data);
		
	}else{
		
		
		//添加数据
        $data = array(
          'number'=>$number,
          'money'=>$money,
          'total_money'=>$total_money,
          'task_id'=>$task_id,
          'uid'=>$member['uid'],
          'add_time'=>time(),
          'is_over'=>0,
          'is_back'=>0,
          
        );
        $res2 = \db('seepackage')->insert($data);
	}
        if(!$res2){
            Db::rollback();
            message('发红包失败:-4','','error');
        }
        
        Db::commit();
        message('发红包成功','reload','success');
    }






  
}